#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/4 9:24
# file: router.py
# author: lotus163
from typing import List

from backend.schemas.system.menu import SysRouterSch, SysMenuSch, RouterMetaSch
from backend.utils.string_util import is_http


class RouterService:

    def get_routers(self, menus_sch: List[SysMenuSch], parent_id: int = 0) -> List[SysRouterSch]:
        routers = []
        for menu_sch in menus_sch:
            if (menu_sch.parentId == parent_id) and (menu_sch.menuType == "M" or menu_sch.menuType == "C"):
                router = self._get_router(menu_sch)
                router.children = self.get_routers(menus_sch, parent_id=menu_sch.menuId)
                if router.children:
                    router.redirect = "noRedirect"
                routers.append(router)
        return routers

    def _get_router(self, menu_sch: SysMenuSch):
        if menu_sch.menuType == "M":
            alwaysShow = True
        else:
            alwaysShow = None
        if (menu_sch.parentId == 0) and (not is_http(menu_sch.path)):
            path = "/" + menu_sch.path
        else:
            path = menu_sch.path
        name = menu_sch.path.title()
        component = menu_sch.component
        if menu_sch.component is None:
            component = "Layout"
        if name == "Log":
            component = "ParentView"
        meta = RouterMetaSch(icon=menu_sch.icon,
                             link=is_http(menu_sch.path),
                             title=menu_sch.menuName,
                             noCache=self.__get_noCache_by_str(menu_sch.isCache))
        router = SysRouterSch(
            alwaysShow=alwaysShow,
            component=component,
            hidden=self.__get_visible_by_str(menu_sch.visible),
            meta=meta,
            name=name,
            path=path
        )
        return router

    def __get_visible_by_str(self, visible: str):
        if visible == "1":
            return True
        else:
            return False

    def __get_noCache_by_str(self, isCache: str):
        if isCache == "1":
            return True
        else:
            return False
